package com.tebiecloud.order.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.*;
import com.tebiecloud.mpweixin.client.constants.MpweixinConstants;
import com.tebiecloud.order.client.model.entity.OrderGoods;
import com.tebiecloud.order.client.model.entity.OrderWriteOffLog;
import com.tebiecloud.order.client.model.entity.Orderr;
import com.tebiecloud.order.client.model.vo.OrderGoodsVO;
import com.tebiecloud.order.client.model.vo.OrderList;
import com.tebiecloud.order.client.model.vo.RightDetail;
import com.tebiecloud.order.client.model.vo.RightList;
import com.tebiecloud.order.server.service.*;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.order.server.service.feign.RetailOrderServiceClient;
import com.tebiecloud.order.server.service.feign.StoreFlowServiceClient;
import com.tebiecloud.order.server.service.feign.StoreServiceClient;
import com.tebiecloud.retail.client.constants.RetailConstants;
import com.tebiecloud.retail.client.model.entity.RetailOrder;
import com.tebiecloud.store.client.model.entity.Store;
import com.tebiecloud.store.client.model.entity.StoreFlow;
import com.tebiecloud.store.client.model.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.aspectj.weaver.ast.Or;
import org.bouncycastle.crypto.engines.AESEngine;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 订单商品信息 前端控制器
 * @author tebie
 * @date 2019-09-15
 */
@Slf4j
@RestController
@RequestMapping("/ordergoods")
public class OrderGoodsController {

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private OrderrService orderrService;

    @Autowired
    private OrderStats1Service orderStats1Service;

    @Autowired
    private OrderStats2Service orderStats2Service;

    @Autowired
    private OrderWriteOffLogService orderWriteOffLogService;

    @Autowired
    private StoreServiceClient storeServiceClient;

    @Autowired
    private RetailOrderServiceClient retailOrderServiceClient;

    @Autowired
    private StoreFlowServiceClient storeFlowServiceClient;

    @Autowired
    private RedisUtils redisUtils;

    /**
     *  我的权益列表
     *  会员权益列表
     * @param userId //
     * @param storeId
     * @param lng
     * @param lat
     * @return
     */
    @PostMapping(value = "listrights")
    public ResultBody<List<RightList>> listrights(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "storeId", required = false) Long storeId,
            @RequestParam(value = "lng", required = false) Double lng,
            @RequestParam(value = "lat", required = false) Double lat) {
        List<RightList> rightLists = new ArrayList<>();
        //获取当前用户
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        Long currentUserId = null;
        if(userId!=null){
            currentUserId = userId;
        }else{
            currentUserId = securityUserDetails.getUserId();
        }
        //获取我的拥有权益
        List<OrderGoods> orderGoodsList = orderGoodsService.listByOrderId(null,currentUserId);
        if(orderGoodsList.size()==0){
           return ResultBodyUtils.ok(rightLists);
        }
       String storeIds = "";
        if(storeId!=null){
            storeIds = storeId.toString();
        }else{
            for(OrderGoods orderGoods:orderGoodsList){
                if(StringUtils.isEmpty(storeIds)){
                    storeIds = orderGoods.getStoreId().toString();
                }else{
                    storeIds = storeIds + "," + orderGoods.getStoreId();
                }
            }
        }
        //获取所有门店信息按照距离排序
        ResultBody<List<StoreVO>>   listResultBody =  storeServiceClient.listBynearby(lng,lat,storeIds);
        if(listResultBody!=null && listResultBody.getCode() == ResultEnum.OK.getCode()){
            List<StoreVO> storeVOList = listResultBody.getData();
            if(storeVOList.size()>0){
                for(StoreVO storeVO:storeVOList){
                    RightList rightList = new RightList();
                    //权益列表
                    List<OrderGoodsVO> orderGoodsVOList =  new ArrayList<>();
                    String distance = "";
                    if(lat!=null && lng!=null && lat!=-1 && lng!=-1){
                        distance = DistanceUtils.getDistance(lng,lat,storeVO.getLng(),storeVO.getLat());
                    }
                    rightList.setDistance(distance);
                    rightList.setStoreName(storeVO.getStoreName());
                    QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
                    orderGoodsQueryWrapper.eq("user_id",currentUserId);
                    orderGoodsQueryWrapper.eq("store_id",storeVO.getStoreId());
                    orderGoodsQueryWrapper.eq("sold",1);
                    orderGoodsQueryWrapper.gt("remain_write_off_times",0);
                    List<OrderGoods> orderGoodsList2 = orderGoodsService.list(orderGoodsQueryWrapper);
                    for(OrderGoods orderGoods:orderGoodsList2){
                        for(int i=0;i<orderGoods.getRemainWriteOffTimes();i++){
                            OrderGoodsVO orderGoodsVO = BeanConvertUtils.copy(orderGoods,OrderGoodsVO.class);
                            orderGoodsVOList.add(orderGoodsVO);
                        }
                    }
                    rightList.setOrderGoodsList(orderGoodsVOList);
                    rightLists.add(rightList);
                }
            }
        }
        return ResultBodyUtils.ok(rightLists);
    }

    /**
     * 通过个人动态码获取对应的权益
     * @param dynamicNo
     * @param storeId
     * @return
     */
    @PostMapping(value = "listRightsByCode")
    public ResultBody listRightsByCode(
            @RequestParam("dynamicNo") String dynamicNo,
            @RequestParam("storeId") long storeId) {
        if(StringUtils.isNotEmpty(dynamicNo)){
            if(dynamicNo.indexOf("tebie_")==-1){
                return ResultBodyUtils.failed("权益码无效");
            }
        }else {
            return ResultBodyUtils.failed("权益码无效");
        }
        long customerUserId = DigitUtils.obj2Long(redisUtils.get(MpweixinConstants.REDIS_WRITE_OFF_ + dynamicNo), -1);
        if(customerUserId <= 0) {
            return ResultBodyUtils.failed("权益码已过期");
        }
        //查询全部
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("user_id",customerUserId);
        orderGoodsQueryWrapper.eq("store_id",storeId);
        orderGoodsQueryWrapper.eq("sold",1);
        orderGoodsQueryWrapper.gt("remain_write_off_times",0);
        List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
        //返回
        List<OrderGoods> orderGoodsList1 = new ArrayList<>();
        for(OrderGoods orderGoods:orderGoodsList){
            for(int i=0;i<orderGoods.getRemainWriteOffTimes();i++){
                OrderGoods orderGoods1 = new OrderGoods();
                BeanUtils.copyProperties(orderGoods,orderGoods1);
                orderGoodsList1.add(orderGoods1);
            }
        }
        return ResultBodyUtils.ok(orderGoodsList1);
    }

    /**
     * 权益详情
     * @param orderGoodsId
     * @return
     */
    @PostMapping(value = "rightsdetail")
    public ResultBody rightsdetail(
            @RequestParam(value = "orderGoodsId") long orderGoodsId,
            @RequestParam(value = "orderWriteOffId",required = false) Long orderWriteOffId) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        RightDetail rightDetail = new RightDetail();
        //查询权益
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_goods_id",orderGoodsId);
        OrderGoods orderGoods = orderGoodsService.getOne(orderGoodsQueryWrapper);
        if(orderGoods==null)return ResultBodyUtils.failed("查询记录不存在");
        //查询核销记录
        OrderWriteOffLog orderWriteOffLog = null;
        if(orderWriteOffId!=null){
            QueryWrapper<OrderWriteOffLog> orderWriteOffLogQueryWrapper = new QueryWrapper<>();
            orderWriteOffLogQueryWrapper.eq("order_write_off_id",orderWriteOffId);
            orderWriteOffLog = orderWriteOffLogService.getOne(orderWriteOffLogQueryWrapper);
        }
        //查询订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("order_id",orderGoods.getOrderId());
        Orderr orderr = orderrService.getOne(orderrQueryWrapper);
        BeanUtils.copyProperties(orderGoods,rightDetail);
        rightDetail.setPhone(orderr.getPhone());
        rightDetail.setReceiver(orderr.getReceiver());
        rightDetail.setReceiverHeadimgurl(orderr.getReceiverHeadimgurl());
        if(orderWriteOffLog!=null){
            rightDetail.setWriteOffTime(orderWriteOffLog.getCt());
            rightDetail.setUsername(orderWriteOffLog.getUserName());
        }
        //查询门店信息
        ResultBody<List<Store>>  listResultBody = storeServiceClient.selectStoreList(orderGoods.getStoreId().toString());
        if(listResultBody.getCode() == ResultEnum.OK.getCode()){
            List<Store> storeList = listResultBody.getData();
            if(storeList!=null && storeList.size()>0){
                rightDetail.setAddress(storeList.get(0).getAddress());
                rightDetail.setStoreName(storeList.get(0).getName());
                rightDetail.setLat(storeList.get(0).getLat());
                rightDetail.setLng(storeList.get(0).getLng());
                rightDetail.setOpenEtime(storeList.get(0).getOpenEtime());
                rightDetail.setOpenStime(storeList.get(0).getOpenStime());
                rightDetail.setStorePhone(storeList.get(0).getStorePhone());
            }
        }
        return ResultBodyUtils.ok(rightDetail);
    }

    /**
     * 核销接口
     * @param orderGoodsId
     * @return
     */
    @PostMapping(value = "update")
    public ResultBody update(@RequestParam(value = "orderGoodsId") long orderGoodsId) {

        //当前人信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        //查询权益
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_goods_id",orderGoodsId);
        OrderGoods orderGoods = orderGoodsService.getOne(orderGoodsQueryWrapper);
        if(orderGoods == null)return ResultBodyUtils.failed("权益不存在！");
        if(orderGoods.getRemainWriteOffTimes()<=0)return ResultBodyUtils.ok("该权益已核销！");
        //查看有效日期
        long perennial = System.currentTimeMillis();
        if(orderGoods.getIsPerennial()!=null && orderGoods.getIsPerennial().equals(0)
                && orderGoods.getCodeEtime()!=null && orderGoods.getCodeStime() != null){
            if(perennial > orderGoods.getCodeEtime().getTime()){
                return ResultBodyUtils.failed("权益有效期已过，不能被核销！");
            }
            if(perennial < orderGoods.getCodeStime().getTime()){
                return ResultBodyUtils.failed("权益有效期未到，不能被核销！");
            }
        }
        //查询订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("order_id",orderGoods.getOrderId());
        Orderr orderr = orderrService.getOne(orderrQueryWrapper);
        if(orderr == null)return ResultBodyUtils.failed("权益对应订单不存在！");
        if(orderr.getStatus()<2 || orderr.getStatus()>=5)return ResultBodyUtils.ok("订单状态不能被核销！");
        //核销接口
        UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper = new UpdateWrapper<>();
        orderGoodsUpdateWrapper.eq("order_goods_id",orderGoodsId);
        OrderGoods orderGoods1 = new OrderGoods();
        orderGoods1.setRemainWriteOffTimes(orderGoods.getRemainWriteOffTimes()-1);
        if(orderGoodsService.update(orderGoods1,orderGoodsUpdateWrapper)){
            //添加核销记录
            OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
            orderWriteOffLog.setOrderId(orderr.getOrderId());
            orderWriteOffLog.setOrderGoodsId(orderGoodsId);
            orderWriteOffLog.setPayType(orderr.getPayType());
            //每次核销一个所以金额为商品单价
            orderWriteOffLog.setPrice(orderGoods.getGoodsPrice());
            orderWriteOffLog.setReceiver(orderr.getReceiver());
            orderWriteOffLog.setReceiverHeadimgurl(orderr.getReceiverHeadimgurl());
            orderWriteOffLog.setStoreId(orderGoods.getStoreId());
            orderWriteOffLog.setUserId(securityUserDetails.getUserId());
            orderWriteOffLog.setUserName(securityUserDetails.getNickName());
            orderWriteOffLogService.save(orderWriteOffLog);
            //处理订单
            if(orderr.getStatus()==2){
                //处理订单状态
                UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                orderrUpdateWrapper.eq("order_id",orderGoods.getOrderId());
                Orderr orderr1 = new Orderr();
                orderr1.setStatus(4);
                orderr1.setWritOffTime(new Date());
                orderrService.update(orderr1,orderrUpdateWrapper);
                //分销费用
                int shareAmount = 0;
                //门店获得资金
                int amount = orderr.getPrice();
                //手续费=订单总金额*6/1000;
                int fees = orderr.getPrice()*6/1000;
                ResultBody<RetailOrder> retailOrderResultBody = retailOrderServiceClient.getRetailOrder(orderr.getOrderId());
                if(retailOrderResultBody!=null && retailOrderResultBody.getCode() == ResultEnum.OK.getCode()){
                    RetailOrder retailOrder = retailOrderResultBody.getData();
                    if(retailOrder!=null){
                        shareAmount = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                        int price = orderr.getPrice()==null?0:orderr.getPrice();
                        int profit = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                        amount = price - profit;
                    }
                }
                log.info(">> minjie 核算后的门店资金：{}，分销费用：{}，手续费：{}",amount,shareAmount,fees);
                //处理流水
                String des = "核销人userId："+securityUserDetails.getUserId()+"；核销人名称："+securityUserDetails.getNickName();
                storeFlowServiceClient.saveStoreFlow(orderr.getStoreId(),amount,shareAmount,fees,
                        1, orderGoods.getOrderId(),des,Integer.valueOf(DateUtils.formatYear()),
                        Integer.valueOf(DateUtils.formatMonth()),Integer.valueOf(DateUtils.formatDay()));
                //更新门店资金
                ResultBody<Store> retStrore = storeServiceClient.updateStoreBalance(orderr.getStoreId(),amount);
                if(retStrore.getCode() != ResultEnum.OK.getCode()){
                    log.info(">>minjie 更新门店资金出错,storeId:{},balance:{}",orderr.getStoreId(),orderr.getPrice());
                }
                //处理分销
                retailOrderServiceClient.updateRetailOrder(orderr.getOrderId(), RetailConstants.RETAIL_ORDER_WRITEOFF);//已核销
                //添加门店业绩
                orderStats2Service.createOrUpdate(orderr,1,0);
            }
            //扣减会员待核销权益
            log.info(">>minjie 核销扣减会员待核销金额：userId:{},storeId:{},goodsPrice:{}",orderr.getUserId(),orderr.getStoreId(),orderGoods.getGoodsPrice());
            orderStats1Service.createOrUpdate(null,orderr.getUserId(),orderr.getStoreId(),null,null,null,0,-orderGoods.getGoodsPrice());
            return ResultBodyUtils.ok(orderWriteOffLog);
        }
        return ResultBodyUtils.failed("核销失败");
    }

}
